'use strict';

var localVideo = document.getElementById("localVideo");
var pushBtn = document.getElementById("pushBtn");

pushBtn.addEventListener("click", startPush);

var uid = $("#uid").val();
var streamName = $("#streamName").val();
var audio = $("#audio").val();
var video = $("#video").val();
var offer = "";
var pc;
const config = {};
var localStream;
var lastConnectionState = "";

function startPush() {
    console.log("send push: /signaling/push");

    $.post("/signaling/push",
        { "uid": uid, "streamName": streamName, "audio": audio, "video": video },
        function (data, textStatus) {
            console.log("push response: " + JSON.stringify(data));
            if ("success" == textStatus && 0 == data.errNo) {
                $("#tips1").html("<font color='blue'>推流请求成功!</font>");
                console.log("offer sdp: \n" + data.data.sdp);
                offer = data.data;
                pushStream();
            } else {
                $("#tips1").html("<font color='red'>推流请求失败!</font>");
            }
        },
        "json"
    );
}

function sendAnswer(answerSdp) {
    console.log("send answer: /signaling/sendanswer");

    $.post("/signaling/sendanswer",
        { "uid": uid, "streamName": streamName, "answer": answerSdp, "type": "push" },
        function (data, textStatus) {
            console.log("send answer response: " + JSON.stringify(data));
            if ("success" == textStatus && 0 == data.errNo) {
                $("#tips3").html("<font color='blue'>answer发送成功!</font>");
            } else {
                $("#tips3").html("<font color='red'>answer发送失败!</font>");
            }
        },
        "json"
    );
}

async function pushStream() {
    try {
        const screenConstraints = {
            video: {
                cursor: "always",
                displaySurface: "monitor" // 可选: monitor, window, application, browser
            },
            audio: false // Chrome 中系统音频需用户手动开启“捕获标签音频”
        };

        const stream = await navigator.mediaDevices.getDisplayMedia(screenConstraints);

        // 成功获取屏幕流
        handleSuccess(stream);

    } catch (err) {
        console.error("屏幕共享失败:", err);
        if (err.name === "AbortError") {
            $("#tips1").html("<font color='red'>屏幕共享被取消。</font>");
        } else if (err.name === "NotAllowedError") {
            $("#tips1").html("<font color='red'>未授权屏幕共享，请重试并允许权限。</font>");
        } else {
            $("#tips1").html("<font color='red'>错误: " + err.message + "</font>");
        }
    }
}

function handleSuccess(stream) {
    localStream = stream;
    localVideo.srcObject = stream;

    // 创建 RTCPeerConnection
    pc = new RTCPeerConnection(config);

    pc.oniceconnectionstatechange = function (e) {
        const state = lastConnectionState
            ? `${lastConnectionState} -> ${pc.iceConnectionState}`
            : pc.iceConnectionState;
        $("#tips2").html("连接状态: " + state);
        lastConnectionState = pc.iceConnectionState;
    };

    // 添加流中的所有轨道（视频 + 可能的音频）
    stream.getTracks().forEach(track => {
        pc.addTrack(track, stream);
    });

    // 设置远端 Offer
    const offerDesc = new RTCSessionDescription(offer);
    pc.setRemoteDescription(offerDesc)
        .then(() => {
            console.log("远程描述设置成功");
            return pc.createAnswer();
        })
        .then(answer => {
            console.log("pc set local sdp");
            console.log("answer sdp: \n" + answer.sdp);
            return pc.setLocalDescription(answer);
        })
        .then(() => {
            console.log("本地 Answer 设置成功");
            sendAnswer(pc.localDescription.sdp);
        })
        .catch(err => {
            console.error("处理 SDP 失败:", err);
            createSessionDescriptionError(err);
        });
}

function handleError(error) {
    console.log("get user media error: " + error);
}

function setRemoteDescriptionSuccess() {
    console.log("pc set remote description success");
    console.log("request screen share");
    window.postMessage({ type: "SS_UI_REQUEST", text: "push" }, "*");
}

function setLocalDescriptionSuccess() {
    console.log("set local description success");
}

function setRemoteDescriptionError(error) {
    console.log("pc set remote description error: " + error);
}

function setLocalDescriptionError(error) {
    console.log("pc set local description error: " + error);
}

function createSessionDescriptionError(error) {
    console.log("pc create answer error: " + error);
}